from odoo import fields, models, api, _
from odoo.exceptions import UserError
import itertools

class WorkflowCheckWizard(models.TransientModel):
    _inherit = "workflow.check.wizard"

    rule_lines = fields.One2many('s.workflow.check.rule.line', 'check_id', string='替换方案')

    @api.model
    def default_get(self, fields):
        res = super(WorkflowCheckWizard, self).default_get(fields)
        if res.get('is_plan', False) and res.get('workflow_type') == 'sale':
            sb_workflow_item_id = self.env.context.get('sb_workflow_item_id')
            sale_order = self.env['sb.workflow.item'].browse(sb_workflow_item_id).sb_workflow_id.sale_order_id
            rule_lines = sale_order.get_rule_lines()
            res.update({
                'rule_lines': rule_lines
            })
        return res

    def approval_pass(self):
        error_list = []
        rule_lines = self.env['s.workflow.check.rule.line'].sudo()
        for product_id, lines in itertools.groupby(self.rule_lines, key=lambda k: k.product_id):
            for line in list(lines):
                rule_lines |= line
            if len(rule_lines.filtered(lambda x: x.checked)) > 1:
                error_list.append(product_id.name)
        if error_list:
            raise UserError('每个原物料只允许勾选一个目标物料，以下不满足：\n' + '\n'.join(error_list))
        self.sb_workflow_item_id.sb_workflow_id.sale_order_id.write({'wizard_id': self.id})
        super(WorkflowCheckWizard, self).approval_pass()

class WorkflowCheckRuleLine(models.TransientModel):
    _name = 's.workflow.check.rule.line'
    _description = 'Replace Rules'

    check_id = fields.Many2one('workflow.check.wizard', string='Check Wizard')
    product_id = fields.Many2one('product.product', string='原物料')
    detail_lines = fields.One2many('s.workflow.check.rule.line.detail', 'line_id', string='适配明细')
    rule_id = fields.Many2one('product.replace.rule', string='替换规则')
    target_product_id = fields.Many2one('product.product', string='目标物料')
    qty = fields.Float(string='需求数量')
    total_price = fields.Float(string='总价')
    diff_price = fields.Float(string='价格差异')
    on_hand = fields.Float(string='库存数量')
    checked = fields.Boolean(string='启用', default=False)
    optional_materials = fields.Many2many('product.product', 's_check_rule_line_optional_meterials', string='可选物料')
    error_info = fields.Text(string='异常内容')

    @api.depends('detail_lines')
    def _compute_target_product_id(self):
        for rec in self:
            checked_lines = rec.detail_lines.filtered(lambda x: x.checked)
            rec.target_product_id = checked_lines[0].target_product_id if checked_lines else False

class WorkflowCheckRuleLineDetail(models.TransientModel):
    _name = 's.workflow.check.rule.line.detail'
    _description = 'Replace Rules'

    line_id = fields.Many2one('s.workflow.check.rule.line', string='Rule Line')
    rule_id = fields.Many2one('product.replace.rule', string='替换规则')
    target_product_id = fields.Many2one('product.product', string='目标物料')
    qty = fields.Float(string='需求数量')
    total_price = fields.Float(string='总价')
    diff_price = fields.Float(string='价格差异')
    on_hand = fields.Float(string='库存数量')
    checked = fields.Boolean(string='启用', default=False)
    optional_materials = fields.Many2many('product.product', 's_rule_line_optional_meterials', string='可选物料')
    error_info = fields.Text(string='误差内容')
